package com.fieldchain.ex.fa100.utils.chart.utils.data;

import com.fieldchain.ex.fa100.utils.chart.dataset.MyLine10DataSet;
import com.fieldchain.ex.fa100.utils.chart.dataset.MyLine5DataSet;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/10/16
 */
public class DataParsePrice {
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    public CombinedData getData(List<List<String>> mList) {
        if(mList.size()>3) {
            long t1 = Long.parseLong(mList.get(0).get(0));
            long t2 = Long.parseLong(mList.get(1).get(0));
            long t3 = Long.parseLong(mList.get(2).get(0));
            int day = 60 * 60 * 24*1000;
            if ((t2 - t1) > day && (t3 - t2) > day) {
                sdf = new SimpleDateFormat("MM-dd");
            } else {
                sdf = new SimpleDateFormat("HH:mm");
            }
        }
        CombinedData combinedData = new CombinedData();
        List<Entry> lineValue5 = new ArrayList<>();
        List<Entry> linePrice = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            List<String> k = mList.get(i);
            float close = Float.parseFloat(k.get(4));
            lineValue5.add(new Entry(i, getMA(i, 5, mList)));
            Long time=Long.parseLong(k.get(0));

            linePrice.add(new Entry(i, close,sdf.format(time)));
        }
        LineData lineData = new LineData();
        MyLine5DataSet lineDataSet5 = new MyLine5DataSet(lineValue5, "5m");
        MyLine10DataSet lineDataSetPrice = new MyLine10DataSet(linePrice, "price");


        initLindata(lineDataSet5, KlineIndex.m1);
        initLindata(lineDataSetPrice, KlineIndex.m3);
        lineData.addDataSet(lineDataSetPrice);
        lineData.addDataSet(lineDataSet5);
        combinedData.setData(lineData);


        return combinedData;
    }

    private float getMA(int index, int ma, List<List<String>> mList) {
        int count = 1;
        float sum = Float.parseFloat(mList.get(index).get(1));
        while (count < ma) {
            if (--index < 0) {
                break;
            }
            sum += Float.parseFloat(mList.get(index).get(1));
            count++;
        }
        return sum / count;
    }


    public void initLindata(LineDataSet dataSet, int color) {
        dataSet.setColor(color);
        dataSet.setLineWidth(1.5f);
        dataSet.setHighlightEnabled(false);
        dataSet.setHighlightLineWidth(1f);
        dataSet.setHighLightColor(KlineIndex.hight);
        dataSet.setDrawValues(false);
        dataSet.setDrawCircles(false);
    }
}
